//脚本唯一关键字,通过该关键字找到对应脚本，每个脚本必须有该描述。
var v_script_id = 'user_3';
//脚本状态,0:该脚本不许执行，1:该脚本可以执行
var v_status = '1';

//脚本逻辑写在run语句之间
if (run && action.getAuthority().is(3,"1")){
	var user = action.getSession().getAttribute("user");
	var username = action.form.getString('username');
	//var password = action.form.getString('password');
	var password = com.handy.util.CryptTool.md5("123456");
	var realname = action.form.getString('realname');
	var gender = action.form.getString('gender');
	var phone = action.form.getString('phone');
	var email = action.form.getString('email');
	var endtime = action.form.getString('endtime');
	var state = action.form.getString('state');
	var roleid = action.form.getString('roleid');
	var arr_roleid = roleid.split(",");
	var rolelist = action.buildArrayList();
	var flag = false;
	var roleids = '';
	var sql = "insert into h_auth_users( "  +
			"username,password,realname,gender,phone,email,createtime,endtime,state,userid) values ('"+ 
			username+"','"+password+"','"+realname+"','"+gender+"','"+
			phone+"','"+email+ "',sysdate,to_date('"+endtime+"','yyyy-mm-dd'),'"+state+"',"+user.getId()+")";
   //print(sql);
   var userid = action.dbUtil.updateAndFindMaxID("","h_auth_users", sql);
   if(userid == 0){
		action.errorCode = 2;//数据库操作失败
		action.retString = '数据库操作失败';//错误文字说明
	}else{
		if(null!=roleid && ""!=roleid){
			//取出可用的所有ROLEID
			if(user.username=='admin' || user.username=='dev'){
				rolelist = action.dbUtil.findColumnBy("","select * from h_auth_roles " ,"id", null);
			}else{
				rolelist = action.dbUtil.findColumnBy("","select * from h_auth_roles where userid=" +user.id  ,"id", null);
			}
			for(i=0; i<arr_roleid.length; i++){
				for(j=0;j<rolelist.size();j++){
					if (arr_roleid[i].equals(java.lang.String.valueOf(rolelist.get(j)))){
						if(roleids=='')
				 			roleids += arr_roleid[i];
				 		else
				 			roleids += arr_roleid[i] + ',';
					}
				}
			}
			 
			if(roleids!='') {
				sql = "insert into h_auth_role_users(roleid,userid) values(?,"+userid+")";
				if(action.dbUtil.batchUpdate("",sql,roleids,",")==0) 
				{
					action.errorCode = 2;//数据库操作失败
					action.retString = '数据库操作失败';//错误文字说明
				};
			}else{
				action.errorCode = 2;//数据库操作失败
				action.retString = '角色不存在或权限不足';//错误文字说明
			}
		}
	}
	
}